package com.sx.rabbitmqtest.mq;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import com.sx.rabbitmqtest.bean.Order;
import com.sx.rabbitmqtest.bean.OrderStatus;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;


@Component
public class OrderConsumer {
    @Autowired
    private RedisTemplate redisTemplate;

    @RabbitHandler
    @RabbitListener(queues = RabbitMQConfig.RABBIT_QUEUE_DL)
    public void receive(Message msg, Channel channel) throws IOException {
        System.out.println("receive msg:" + new String(msg.getBody()) + " with tag:" + msg.getMessageProperties().getDeliveryTag() + " with id:" + msg.getMessageProperties().getCorrelationId());
        JSONObject jsonObject = JSON.parseObject(new String(msg.getBody()));
        Order o = jsonObject.toJavaObject(Order.class);
        Order order = (Order)redisTemplate.opsForValue().get("order:" + o.getUserId() + ":" + o.getOrderId());
        if(order !=null && order.getOrderStatus() == OrderStatus.PAYING){
            order.setOrderStatus(OrderStatus.TIMEOUT);
            redisTemplate.opsForValue().set("order:" + o.getUserId() + ":" + o.getOrderId(), order);
        }
        channel.basicAck(msg.getMessageProperties().getDeliveryTag(), false);
    }
}
